/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 15:35:36
 * @Auditor:
 */
import React, { useRef, useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import JsBarcode from 'jsbarcode';
import { InputProps as AntdInputProps } from 'antd/lib/input';
import { FormItemProps } from 'antd/lib/form';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';

const QRCode = require('qrcode.react')

interface LinkInputProps extends AntdInputProps {
  initialValue?: string;
}

interface CodeRefProps {
  setData(code?: string): void
}

export interface CodeProps extends CanvasItemProps {
  codeProps?: LinkInputProps;
  formItemProps?: FormItemProps;
}

const App = (props: CodeProps, ref: React.Ref<CodeRefProps>) => {
  const { codeProps, formItemProps, domComplete, isDesign, ...canvasProps } = props;

  useQueryControlWrap(canvasProps.id, '', domComplete);

  const refs = useRef(null)
  const [code, setCode] = useState<null | string>(null)
  const [type, setType] = useState<null | string>(null)

  useImperativeHandle(ref, () => ({
    setData(value?: string) {
      if(value) setCode(value)
    }
  }));

  useEffect(() => {
    if (!code || type !== 'barCode') return
    try {
      JsBarcode(refs.current, isDesign ? 'welinkin' : code!, {
        displayValue: false,
        width: 1.5,
        height: 50,
        margin: 0,
      });
    } catch (error) {
      console.log(error);
    }
  }, [code, type, isDesign])

  useEffect(() => {
    if (codeProps?.initialValue) setCode(codeProps.initialValue)
    if (codeProps?.type) setType(codeProps.type)
  }, [codeProps])

  useEffect(() => {
    if (formItemProps?.initialValue) setCode(formItemProps.initialValue)
  }, [formItemProps])

  let _code = isDesign ? 'welinkin' : code;

  return (
    <div {...canvasProps} {...formItemProps} >
      {
        _code ? type === 'barCode' ? <div ><svg ref={refs} />  </div> : <QRCode
          value={_code}
          size={100}
        /> : null
      }
    </div>
  );
};

export default forwardRef(App);


